package com.company.linkedlist.model;

/**
 * @author shenhan
 * @create 2020/1/28 13:19
 * @description
 */
public class DoubleLinkedList {
    private Node head = new Node(0, "", "");

    public Node getHead() {
        return head;
    }

    // 遍历双向链表
    public void list() {
        if (head.next == null) {
            System.out.println("链表为空");
            return;
        }
        Node temp = head.next;
        while (temp != null) {
            System.out.println(temp.toString());
            temp = temp.next;
        }
    }

    // 添加到末尾
    public void add(Node node) {
        Node temp = head;
        while (true) {
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
        temp.next = node;
        node.pre = temp;
    }

    public void update(Node heroNode) {
        if (head.next == null) {
            System.out.println("链表为空，直接添加");
            add(heroNode);
        }
        Node temp = head.next;
        boolean flag = false;
        while (true) {
            if (temp == null) {
                break;
            }
            if (temp.no == heroNode.no) {
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if (flag) {
            temp.name = heroNode.name;
            temp.nickName = heroNode.nickName;
        } else {
            System.out.printf("没有找到编号为%d的hero", heroNode.no);
        }
    }

    /**
     * 直接找到，自我删除
     *
     * @param no
     */
    public void delete(int no) {
        // 判断是否为空链表
        if (head.next == null) {
            System.out.println("链表为空，无法删除");
            return;
        }
        Node temp = head.next;
        boolean flag = false;
        while (true) {
            if (temp == null) {
                break;
            }
            if (temp.no == no) {
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if (flag) {
            temp.pre.next = temp.next;
            if (temp.next != null) {
                temp.next.pre = temp.pre;
            }
        } else {
            System.out.println("不存在");
        }

    }

}
